package com.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import event.MessageEvent;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activity.adapter.OpusDetailAdapter;
import com.activity.bean.OpusBean;
import com.activity.bean.RemarkBean;
import com.api.param.CommentParam;
import com.api.param.RemarkParam;
import com.api.viewModel.LoginVM;

import com.example.apple.ddhr_new.MainActivity;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.setting.BaseListViewActivity;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.CommonUtils;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.google.gson.Gson;

import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent;
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEventListener;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OpusDetailActivity extends BaseListViewActivity<LoginVM> {

    RemarkParam pageParam =new RemarkParam();
    private LinearLayout edittextbody;
    private EditText editText;
    private TextView sendIv;
    private OpusBean opus;
    private RelativeLayout bodyLayout;
    private int currentKeyboardH;
    private int screenHeight;
    private int editTextBodyHeight;

    private CommentParam param = new CommentParam();
    private CommentParam commentParam = new CommentParam();
    private int slectedIndex;
    private boolean iscomment;
    private View commentView;
    private View replyView;

    @Override
    protected int titleText() {
        return R.string.zuopin_xiangqing;
    }

    private  OpusDetailAdapter opusDetailAdapter;
    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);

        opusDetailAdapter= new OpusDetailAdapter(this);
        Gson gson = new Gson();
        opus =gson.fromJson(getIntent().getExtras().getString("param"),OpusBean.class);
        setTitleText(opus.getUsernickname());
        opusDetailAdapter.opusBean =opus;
        recycleView.setAdapter(opusDetailAdapter);
        param.worksid =  opus.getWorksid();
        commentParam.worksid = opus.getWorksid();
        opusDetailAdapter.listener = new OpusDetailAdapter.ClickListener() {
            @Override
            public void commentClick(View view) {
                iscomment = true;

                commentView =view;
               updateEditTextBodyVisible(View.VISIBLE);
            }

            @Override
            public void praiseClick() {
                CommentParam param1 = new CommentParam();
                param1.worksid = opus.getWorksid();
                addSubscription(listViewModel.addworkspraise(param1,0));
            }

            @Override
            public void replyClick(int groupPosition, int childPosition,View view) {

                replyView =view;
                slectedIndex =childPosition;
                iscomment = false;

                updateEditTextBodyVisible(View.VISIBLE);

            }

            @Override
            public void deleteClick() {
                CommentParam param1 = new CommentParam();
                param1.worksid = opus.getWorksid();
                addSubscription(listViewModel.deleteWorks(param1));
            }

            @Override
            public void editClick() {
                Bundle param = new Bundle();
                Gson gson1 = new Gson();

                param.putString("param",gson1.toJson(opus));

                ActivityUtil.startActivity(OpusDetailActivity.this,OpusPostActivity.class,param);

            }
        };

        listViewModel.deleteWorks.observe(this,res->{
           MessageEvent messageEvent=  new MessageEvent(MessageEvent.MESSAGE_EVENT_DELETE_WORKS);
           messageEvent.worksId = opusDetailAdapter.opusBean.getWorksid();

            EventBus.getDefault().post(messageEvent);
            finish();

        });
        listViewModel.workRemarkError.observe(this,error->{
            if(error){
                headerFreshEnd();
            }else {
                pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)-1)+"";
                footerFreshEnd();
            }
        });
        listViewModel.comment.observe(this,res->{

            if(iscomment){
                opus.setWorksreplynum(res);
                headerFreshing();
            }else {
                RemarkBean remarkBean = opusDetailAdapter.getData().get(slectedIndex);
                RemarkBean.ReplylistBean replylistBean = new RemarkBean.ReplylistBean();
                replylistBean.setUsernickname(App.getInstance().getAccount().getUsernickname());
                replylistBean.setReplycontent(commentParam.content);
                replylistBean.setUsericon(App.getInstance().getAccount().getUsericon());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = simpleDateFormat.format(new Date());
                replylistBean.setReplyaddtime(dateString);
                remarkBean.getReplylist().add(replylistBean);
                opusDetailAdapter.notifyChildChanged(0,slectedIndex);

            }

        });
        listViewModel.praise.observe(this,res->{
            opus.setWorkifpraise(res);
            opusDetailAdapter.notifyGroupChanged(0);

            workDetai();
            MessageEvent messageEvent=  new MessageEvent(MessageEvent.MESSAGE_EVENT_WORK_PRAISE);
            messageEvent.worksId = opusDetailAdapter.opusBean.getWorksid();
            messageEvent.praiseNum = res;
            EventBus.getDefault().post(messageEvent);

        });

        listViewModel.workDetail.observe(this,res->{

            opusDetailAdapter.opusBean =res.getResult().get(0);
            opus = res.getResult().get(0);
            opusDetailAdapter.notifyDataChanged();
        });

        recycleView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (edittextbody.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE);
                    return true;
                }
                return false;
            }
        });


        listViewModel.workRemark.observe(this,data->{

            if(data.isHeader){

                opusDetailAdapter.getData().clear();
                opusDetailAdapter.getData().addAll(data.getResult());

                headerFreshEnd();
            }else
            {
                opusDetailAdapter.getData().addAll(data.getResult());
                if(data.getResult().size()>0){
                    footerFreshEnd();
                }else
                {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
            opusDetailAdapter.notifyDataSetChanged();

//            if(opusDetailAdapter.getData().size()>0){
//                showEmpty(false);
//            }else {
//                showEmpty(true);
//            }




        });
        pageParam.worksid = opus.getWorksid();
        headerFreshing();

        edittextbody = (LinearLayout) findViewById(R.id.editTextBodyLl);
        editText = (EditText) findViewById(R.id.circleEt);
        sendIv = (TextView) findViewById(R.id.sendIv);
        sendIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if(editText.getText().toString().length()>0){
                    updateEditTextBodyVisible(View.GONE);
                    if(iscomment){
                        param.replycontent = editText.getText().toString();
                        param.content =param.replycontent;

                        addSubscription(listViewModel.addworksreply(param));
                        editText.setText("");
                    }else
                    {
                        RemarkBean remarkBean = opusDetailAdapter.getData().get(slectedIndex);


                        commentParam.parentid =remarkBean.getReplyid();
                        commentParam.content =editText.getText().toString();
                        editText.setText("");
                        addSubscription(listViewModel.addworksreply(commentParam));
                    }

                }else {

                }

            }
        });

        setViewTreeObserver();
        workDetai();
    }

    private  void  workDetai(){
        RemarkParam params = new RemarkParam();
        params.worksid = opus.getWorksid();
        addSubscription(listViewModel.workDetail(params));
    }
    private void setViewTreeObserver() {



        final ViewTreeObserver.OnGlobalLayoutListener layoutListener =
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    private final Rect r = new Rect();

                    private boolean wasOpened = false;

                    @Override
                    public void onGlobalLayout() {
                        getWindow().getDecorView().getWindowVisibleDisplayFrame(r);

                        int screenHeight = getWindow().getDecorView().getRootView().getHeight();
                        int heightDiff = screenHeight - r.height();

                        boolean isOpen = heightDiff > screenHeight * 0.15;

                        int statusBarHeight = 0;
                        if (heightDiff > 100) {
                            // 如果超过100个像素，它可能是一个键盘。获取状态栏的高度
                            statusBarHeight = 0;
                        }
                        try {
                            Class<?> c = Class.forName("com.android.internal.R$dimen");
                            Object obj = c.newInstance();
                            Field field = c.getField("status_bar_height");
                            int x = Integer.parseInt(field.get(obj).toString());
                            statusBarHeight = getResources().getDimensionPixelSize(x);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        int realKeyboardHeight = heightDiff - statusBarHeight-ScreenUtil.dp2px(OpusDetailActivity.this,44);

                        if (isOpen == wasOpened) {
                            // keyboard state has not changed
                            return;
                        }

                        wasOpened = isOpen;
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) edittextbody.getLayoutParams();

                        if(isOpen){
                            params.setMargins(0,0,0,realKeyboardHeight);
                        }else {
                            params.setMargins(0,0,0,0);
                        }
                        edittextbody.setLayoutParams(params);

                        if(iscomment&&isOpen){
                            int[] location = new  int[2] ;
                            int[] location1 = new  int[2] ;
                            edittextbody.getLocationInWindow(location); //获取在当前窗口内的绝对坐标
                            commentView.getLocationInWindow(location1);
                            if((location1[1]+commentView.getHeight()+realKeyboardHeight)<location[1]){

                            }else {
//                                ( (LinearLayoutManager)recycleView.getLayoutManager()).scrollToPositionWithOffset(0,((location1[1]+sendIv.getLayoutParams().height)-location[1]));
                              int y=   (location1[1]+commentView.getHeight()+realKeyboardHeight)-location[1];
                                recycleView.smoothScrollBy(0,y+ScreenUtil.dp2px(OpusDetailActivity.this,10));
                            }
                        }

                        if(iscomment==false&&isOpen){
                            int[] location = new  int[2] ;
                            int[] location1 = new  int[2] ;
                            edittextbody.getLocationInWindow(location); //获取在当前窗口内的绝对坐标
                            replyView.getLocationInWindow(location1);
                            if((location1[1]+replyView.getHeight()+realKeyboardHeight)<location[1]){

                            }else {
//                                ( (LinearLayoutManager)recycleView.getLayoutManager()).scrollToPositionWithOffset(0,((location1[1]+sendIv.getLayoutParams().height)-location[1]));
                                int y=   (location1[1]+replyView.getHeight()+realKeyboardHeight)-location[1];
                                recycleView.smoothScrollBy(0,y+ScreenUtil.dp2px(OpusDetailActivity.this,10));
                            }
                        }


                    }
                };
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);



    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    public void updateEditTextBodyVisible(int visibility) {

        edittextbody.setVisibility(visibility);



        if(View.VISIBLE==visibility){
            editText.requestFocus();
            //弹出键盘

            CommonUtils.showSoftInput( editText.getContext(),  editText);



        }else if(View.GONE==visibility){
            //隐藏键盘
            CommonUtils.hideSoftInput( editText.getContext(),  editText);



        }

    }
    /**
     * 获取状态栏高度
     * @return
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    protected void headerFreshing() {
        pageParam.pagenum ="1";
        refreshLayout.resetNoMoreData();
        addSubscription(listViewModel.getWorksReplyList(pageParam,true));
    }

    @Override
    protected void footerFreshing() {
        pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)+1)+"";

        addSubscription(listViewModel.getWorksReplyList(pageParam,false));
    }

    @Override
    public void onMessageEvent(MessageEvent event) {
        super.onMessageEvent(event);
        if(event.getMessage()==MessageEvent.MESSAGE_EVENT_UPDATE_WORKS){
            workDetai();
        }
    }
}
